<?php

namespace app\admin\model\facility;

use think\Model;

/**
 * Form
 */
class Form extends Model
{
    // 表名
    protected $name = 'facility_form';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 追加属性
    protected $append = [
        'facilityDevice',
        'facilityService',
    ];


    public function getFacilityDeviceAttr($value, $row): array
    {
        return [
            'title' => \app\admin\model\facility\Device::whereIn('id', $row['facility_device_ids'])->column('title'),
        ];
    }

    public function getFacilityDeviceIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setFacilityDeviceIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function getFacilityServiceAttr($value, $row): array
    {
        return [
            'title' => \app\admin\model\facility\Service::whereIn('id', $row['facility_service_ids'])->column('title'),
        ];
    }

    public function getFacilityServiceIdsAttr($value): array
    {
        if ($value === '' || $value === null) return [];
        if (!is_array($value)) {
            return explode(',', $value);
        }
        return $value;
    }

    public function setFacilityServiceIdsAttr($value): string
    {
        return is_array($value) ? implode(',', $value) : $value;
    }

    public function user(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\User::class, 'user_id', 'id');
    }

    public function facilityPlace(): \think\model\relation\BelongsTo
    {
        return $this->belongsTo(\app\admin\model\facility\Place::class, 'facility_place_id', 'id');
    }
}